using System.Collections.Generic;
using System.Data;
using System.Linq;
using Magiq.Behaviors;
using Magiq.Insert;

namespace Magiq.Databases.Insert
{
    public class DatabaseInsertBehavior<TSource, TDestination, TNew> : DefaultBehavior,
                                                                       IDatabaseInsertBehavior
                                                                           <TSource, TDestination, TNew>
        where TDestination : class
        where TNew : class
    {
        private IInsert<TSource, TDestination, TNew> insert;

        protected IOrmAdapter OrmAdapter { get; private set; }

        #region IDatabaseInsertBehavior<TSource,TDestination,TNew> Members

        public void Initialize(IOrmAdapter ormAdapter, IInsert<TSource, TDestination, TNew> insert)
        {
            this.insert = insert;
            OrmAdapter = ormAdapter;
        }

        public IEnumerable<DatabaseInsert<TSource>> BuildDatabaseInserts()
        {
            return OrmAdapter.BuildDatabaseInserts(insert);
        }

        public IDbCommand BuildCommand(DatabaseInsert<TSource> insert)
        {
            var builder = new InsertCommandBuilder(typeof (TNew), insert.OrmAdapter, (IQueryable) insert.Source,
                                                   insert.ColumnAssignments);
            return builder.GetCommand();
        }

        #endregion

        protected virtual IEnumerable<InsertColumnsAssignment> CustomAssignments(
            IInsert<TSource, TDestination, TNew> insert)
        {
            yield break;
        }
    }
}